package com.iot.ammeter.service.impl.web.menu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iot.ammeter.constant.Constant;
import com.iot.ammeter.dto.web.menu.MenuDTO;
import com.iot.ammeter.entity.web.menu.Menu;
import com.iot.ammeter.mapper.web.campus.MenuMapper;
import com.iot.ammeter.service.web.menu.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * web端用户菜单导航 服务实现类
 * </p>
 *
 * @author basil
 * @since 2021-09-25
 */
@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    private final MenuMapper menuMapper;

    public MenuServiceImpl(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    /**
     * 根据条件查询菜单
     *
     * @param lambdaQueryWrapper 查询条件
     * @return List
     */
    @Override
    public List<Menu> selectList(LambdaQueryWrapper<Menu> lambdaQueryWrapper) {
        return menuMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 获取菜单列表
     *
     * @return 菜单列表集合
     */
    @Override
    public List<MenuDTO> getMenuList() {
        List<MenuDTO> menuDTOList = menuMapper.getMenuList();
        List<MenuDTO> menuList = new ArrayList<>();
        for (MenuDTO menuDto : menuDTOList) {
            if (menuDto.getParentId().equals(Constant.Menu.PARENT_ID)) {
                menuDto.setSubMenu(findChildren(menuDTOList, menuDto));
                menuList.add(menuDto);
            }
        }
        return menuList;
    }

    /**
     * 递归菜单查找子菜单
     *
     * @param menus   菜单集合
     * @param menuDto 菜单
     * @return 菜单列表
     */
    private List<MenuDTO> findChildren(List<MenuDTO> menus, MenuDTO menuDto) {
        List<MenuDTO> subMenu = new ArrayList<>();
        menus.forEach(item -> {
            if (item.getParentId().equals(menuDto.getMenuId())) {
                item.setSubMenu(findChildren(menus, item));
                subMenu.add(item);
            }
        });
        return subMenu;
    }
}
